import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/auth',
    name: 'Auth',
    component: () => import('@/views/Auth.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    redirect: '/auth'
  },
  {
    path: '/register',
    redirect: '/auth'
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    redirect: (to) => {
      // 如果已登录，重定向到仪表盘；否则重定向到登录页
      const userStore = useUserStore()
      return userStore.isLoggedIn ? '/dashboard' : '/auth'
    },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'rooms',
        name: 'Rooms',
        component: () => import('@/views/Rooms.vue'),
        meta: { title: '房间列表' }
      },
      {
        path: 'guests',
        name: 'Guests',
        component: () => import('@/views/Guests.vue'),
        meta: { title: '客户管理' }
      },
      {
        path: 'reservations',
        name: 'Reservations',
        component: () => import('@/views/Reservations.vue'),
        meta: { title: '预订管理' }
      },
      {
        path: 'services',
        name: 'Services',
        component: () => import('@/views/Services.vue'),
        meta: { title: '服务管理' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: { title: '系统设置' }
      },
      {
        path: 'help',
        name: 'Help',
        component: () => import('@/views/Help.vue'),
        meta: { title: '帮助中心' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  console.log('路由导航:', {
    to: to.path,
    from: from.path,
    isLoggedIn: userStore.isLoggedIn,
    requiresAuth: to.meta.requiresAuth
  })
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false && !userStore.isLoggedIn) {
    console.log('未登录，重定向到登录页')
    next('/auth')
    return
  }
  
  // 如果未登录且访问根路径，重定向到认证页
  if (to.path === '/' && !userStore.isLoggedIn) {
    console.log('未登录访问根路径，重定向到认证页')
    next('/auth')
    return
  }
  
  // 如果已登录且访问认证页，重定向到仪表盘
  if (to.path === '/auth' && userStore.isLoggedIn) {
    console.log('已登录，重定向到仪表盘')
    next('/dashboard')
    return
  }
  
  next()
})

// 路由加载错误处理
router.onError((error) => {
  console.error('路由加载错误:', error)
})

export default router
